package com.example.wanandroid.sharedpreferences

import android.content.Context
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class PrefsProperty<T>(val context: Context, val name: String, private val defValue: T) :
    ReadWriteProperty<Any?, T> {
    private val sharedPreferences: SharedPreferences by lazy {
        context.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        with(sharedPreferences) {
            return when (defValue) {
                is Int -> getInt(name, defValue)
                is Long -> getLong(name, defValue)
                is Float -> getFloat(name, defValue)
                is Boolean -> getBoolean(name, defValue)
                is String -> getString(name, defValue)
                else -> throw IllegalArgumentException("This type can not be saved into Preferences.")
            } as T
        }
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        with(sharedPreferences.edit()) {
            when (value) {
                is Int -> putInt(name, value)
                is Long -> putLong(name, value)
                is Float -> putFloat(name, value)
                is Boolean -> putBoolean(name, value)
                is String -> putString(name, value)
                else -> throw IllegalArgumentException("This type can not be saved into Preferences.")
            }.apply()
        }

    }
}